﻿using System.Linq;
using System.Xml.Linq;
using Mono.Cecil;

namespace ResourceManager
{
    public class NHibernateConfiguration
    {
        #region Constants

        private const string XMLNS = "urn:nhibernate-configuration-2.2";

        #endregion

        #region Variables

        private XElement _node;
        private XElement _sessionFactory;

        #endregion

        #region Constructors

        public NHibernateConfiguration(XElement node)
        {
            _node = node;
            _sessionFactory = node.Element(XName.Get("hibernate-configuration", XMLNS)).Element(XName.Get("session-factory", XMLNS));
        }

        #endregion

        #region Properties

        public string DefaultSchema
        {
            get
            {
                return _sessionFactory.Elements(XName.Get("property", XMLNS)).Where(x => x.Attribute("name").Value == "hibernate.default_schema").Single().Value;
            }
            set
            {
                _sessionFactory.Elements(XName.Get("property", XMLNS)).Where(x => x.Attribute("name").Value == "hibernate.default_schema").Single().Value = value;
            }
        }

        public string ConnectionString
        {
            get
            {
                return _sessionFactory.Elements(XName.Get("property", XMLNS)).Where(x => x.Attribute("name").Value == "hibernate.connection.connection_string").Single().Value;
            }
            set
            {
                _sessionFactory.Elements(XName.Get("property", XMLNS)).Where(x => x.Attribute("name").Value == "hibernate.connection.connection_string").Single().Value = value;
            }
        }

        #endregion

        #region Methods

        public static NHibernateConfiguration FromXml(XElement node)
        {
            return new NHibernateConfiguration(node);
        }

        public static NHibernateConfiguration FromText(string text)
        {
            return new NHibernateConfiguration(text.GetXml());
        }

        public static NHibernateConfiguration FromBytes(byte[] bytes)
        {
            return new NHibernateConfiguration(bytes.GetXml());
        }

        public static NHibernateConfiguration FromResource(EmbeddedResource resource)
        {
            return new NHibernateConfiguration(resource.Data.GetXml());
        }

        public override string ToString()
        {
            return _node.ToString();
        }

        public XElement ToXml()
        {
            return _node;
        }

        #endregion
    }
}